<?php
namespace app\web\model;

use app\lib\model\Price;
/**
 * @package app\basic\model
 */
class UserBalance extends Base 
{
    public function getCreateTimeAttr($v)
    {
        return date('Y-m-d',$v);
    }
    public function getUpdateTimeAttr($v)
    {
        return date('Y-m-d',$v);
    }
    /**
     * [change description]
     * @param  [type]  $user_id        [description]
     * @param  [type]  $change_balance [description]
     * @param  [type]  $balance_type   [description]
     * @param  string  $notes          [description]
     * @param  integer $order_id       [description]
     * @return [type]                  [description]
     */
    public static function change($user_id,$change_balance,$balance_type,$notes = '',$order_id = 0)
    {
        if($change_balance == 0) return true;
        $user = User::get($user_id);
        $after_balance = Price::pricecalc($user->balance,'+',$change_balance);
        if($balance_type == 3){
            $user->withdrawal_balance = Price::pricecalc($user->withdrawal_balance,'+',$change_balance);
        }
        $data = [
            'user_id' => $user_id,
            'balance_type' => $balance_type,
            'order_id' => $order_id,
            'before_balance' => $user->balance,
            'change_balance' => $change_balance,
            'after_balance' => $after_balance,
            'status' => $balance_type == 4 ? 0 : 1,
            'notes' => $notes,
            'appkey' => Config::getAppKey()
        ];
        $res = self::create($data);
        if($res->isEmpty()) return false;
        $user->balance = $after_balance;
        $res = $user->save();
        return $res ? true : false;
    } 
}